﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VisaValeCheck.Library;

namespace VisaValeCheck
{
    public static class CartaoManipulation
    {
        public static System.Collections.ObjectModel.ObservableCollection<NumeroCartao> Cartoes { get; set; }

        public static System.Windows.Threading.Dispatcher _dispatcher = App.Current.Dispatcher;

        static CartaoManipulation()
        {
            if (Cartoes == null)
                Cartoes = new System.Collections.ObjectModel.ObservableCollection<NumeroCartao>();
        }

        private delegate void Anonimous();
        public static System.Collections.ObjectModel.ObservableCollection<NumeroCartao> CarregarCartoes()
        {
            var cartoes = from no in SaldosSerialization.Saldos
                          select no.NumeroCartao;
            Anonimous x = delegate()
            {
                Cartoes.Clear();
                foreach (NumeroCartao cartao in cartoes)
                    Cartoes.Add(cartao);
            };
            _dispatcher.Invoke(x, null);
            return Cartoes;
        }

        public static NumeroCartao UltimoCartaoSelecionado()
        {
            NumeroCartao cartao = null;
            
            if (Cartoes.Count > 0)
                cartao = Cartoes.First((a) => a.Selecionado);

            return cartao;
        }

        public static void ColocarCartaoAtivo(NumeroCartao cartao)
        {
            var cartoesSelecionados = Cartoes.Where(x => x.Selecionado);
            foreach (var c in cartoesSelecionados)
            {
                c.Selecionado = false;
            }

            IEnumerable<NumeroCartao> nCartaoArmazenado = Cartoes.Where((a) => a == cartao);
            if (nCartaoArmazenado.Count() > 0)
                nCartaoArmazenado.First().Selecionado = true;
        }

        public static bool Deletar(NumeroCartao cartao)
        {
            var numCartao = from no in Cartoes
                            where
                            no == cartao
                            select no;
            bool ret = false;
            if (numCartao.Count() > 0)
            {
                SaldosSerialization.Deletar(numCartao.First());
                Cartoes.Remove(numCartao.First());
                ret = true;
            }
            return ret;
        }
    }
}
